package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.AppJwtUtil;
import com.usian.utils.common.AesUtil;
import com.usian.utils.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@PropertySource("classpath:aes.properties")
public class WmUserServiceImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Value("${key}")
    private String key;

    //Wemedia登录业务实现
    //注:其实没有登录的事，就是前端传了个参数，后端校验了一下
    //已经修改了加密方式，使用bcrypt校验，又升级了,admin还是原有的校验方式（具体看admin模块)
    @Override
    public ResponseResult login(WmUserDto dto) {
        //dto  用户名 密码 任意为空 返回错误
        if(dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) return errorParam;
        //返回一条数据
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));

        if(one==null) return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");

        //aes加密的结果(前端)
        String aes = dto.getPassword();
        String md5Result =null;
        try {
            //md5加密结果(后端解密为MD5)
            md5Result = AesUtil.decryptAES(aes, key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //bcrypt的加密加盐结果(数据库)
         String password = one.getPassword();
         //校验:前端和后端数据是否一致，采用bcrypt校验
        boolean checkpw = BCrypt.checkpw(md5Result, password);

        //表单密码和数据库当前用户密码是否保持一致
        if(checkpw){
            //登录成功后，要返回token了
            Map<String,Object> resultMap = new HashMap<>();
            //token的用户id从表中取
            resultMap.put("token", AppJwtUtil.getToken(Long.valueOf(one.getId())));
            //不能返回密码,和盐，这样子很容易让他人推断出来加密算法
            one.setPassword("");
            one.setSalt("");
            //返回当前用户信息
            resultMap.put("user",one);
            return ResponseResult.okResult(resultMap);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
    }
    }
